<template>
	<view class="wuyepay">
		<!-- 顶部 -->
		<view class="head">
			<view class="border-back">
				<view class="position-name" style="padding-bottom: 10px;margin-top: 10px;">
					<image style="width:25px;height:25px;vertical-align: -5px;" 
						src="https://clhy-img.oss-cn-beijing.aliyuncs.com/ownerImage/loufang.png">
					</image>
					<span style="margin-left: 10px;">{{name}}{{address}}</span>
				</view>
				<view class="u-flex u-row-between u-m-t-12">
					<view class="u-font-26 u-margin-bottom-22"><span
							style="color: #999;">业主姓名：</span>{{homelist.ownerName}}</view>
					<view class="u-font-26 u-margin-bottom-22"><span
							style="color: #999;">建筑面积：</span>{{homelist.roomAreaOfStructure}}㎡</view>

				</view>
				<view class="u-flex u-row-between">
					<view class="u-font-26 u-margin-bottom-22">
						<span style="color: #999;">单价：</span><span
							style="color: #f29100;padding-right: 3px;">{{homelist.wuYePrice}}</span>/ ㎡ /
						{{(homelist.costsPeriodUnit==1?'年':homelist.costsPeriodUnit==2?'半年':homelist.costsPeriodUnit==3?'季度':'月')}}
					</view>
					<view class="u-font-26 u-margin-bottom-22"><span style="color: #999;">年物业费：</span>
						<span
							style="color: #f29100;font-size: 18px;padding-right: 3px;">{{Number(payList.normalWuYeMoney).toFixed(2)}}</span>元
					</view>
				</view>
				<view class="btn" @click="show=true"
					v-if="payList.wuYeCost.lenght==0||(payList.wuYeCost.lenght>0&&payList.wuYeCost[0].costSign!=2)">
					预缴费用
				</view>
			</view>
		</view>
		<!-- 主体内容 -->
		<view class="main" v-if="isShow &&payList.wuYeCost.length>0">
			<view class="mian_content" v-for="(item,index) in payList.wuYeCost" :key='index' v-show="!item.freeOrder">
				<view class="u-flex">
					<image style="width: 21px;height: 21px;margin-right: 3px;" src="http://clhy-img.oss-cn-beijing.aliyuncs.com/venusImage/2023-07-04/1688450026332.png" mode="">
					</image>
					<view>
						<span style="color: #999;">{{item.costName}}：</span>￥{{item.periodShouldMoney}}
					</view>
				</view>
				<view style="float: right;margin-top: -18px;">
					<view class="daishenpi" v-if="item.costSign === 1">待缴</view>
					<view class="jujue" v-if="item.costSign === 2">欠费</view>
					<view class="youxiao" v-if="item.costSign === 3">预缴</view>
				</view>
				<view class="u-flex u-m-t-10" style="margin-left: 26px;width:100%;">
					<span style="color: #999;">缴费周期：</span>
					<view>{{item.nextStartTime }}-{{item.nextEndTime }}</view>
				</view>
				<view class="u-flex u-row-between u-m-t-10">
					<view>
						<u-checkbox shape="circle" v-model="item.selectionStatus2" active-color="#427705c7"
							@change="handleAdditional(item,index)"><span style="color: red;margin-left: 8rpx;">违约金：</span>
							￥{{item.weiYueMoney}}</u-checkbox>
					</view>
					<view>
						<span style="color: #999;">违约天数：</span>{{item.arrearageDay}} 天
					</view>
				</view>
				<view v-if="item.chargeList != null"
					style="background-color: #F4f4f4;width: 90%;margin: 9px auto;padding: 10px 20px;">
					<span style="color: blue;">附加费用：</span>
					<view v-for="(item1,index1) in item.chargeList">
						<view class="u-flex u-m-t-10">
							<span style="color: #999;">{{item1.costsSetChildName}}：</span>
							<view>{{item1.costsSetMoney.toFixed(2)}} 元</view>
						</view>
					</view>
				</view>
				<view style="text-align: right;margin-top: 10px;">
					合计：<span
						style="color: orange;padding-right: 2px;font-size:36rpx">{{ Number(item.allMoney).toFixed(2) }}</span>元
				</view>
			</view>
			<view class="property-cost">
				<view style="margin-top:-10rpx;">备注：</view>
				<textarea auto-height class="property-cost-mark" type="textarea" v-model="costRemarks" placeholder="请输入您要备注的内容" />
			</view>
		</view>
		<view v-if="payList.wuYeCost.length==0">
			<view style="width: 232px;height: 242px;margin: 110px auto;">
				<image style="width: 100%;height: 100%;"
					src="https://clhy-file.oss-cn-beijing.aliyuncs.com/5cac27047c7a38893e2e1033b66e723.png" mode="">
				</image>

			</view>
			<view style="width: 62%;margin: -66px auto;text-align: center;color: #999;">暂无缴费数据</view>
		</view>
		<!-- footer -->
		<view class="foot" v-if="isShow">
			<view class="footer u-padding-left-30">
				<view style="display: flex;justify-content:space-between">
					<view class="u-m-t-32 u-font-32 u-m-r-20">合计：<text style="font-size: 44rpx;color: #F9A832;"
							class="txet">￥{{payTotal}}</text></view>
					<view class="button" @click="payBtn">立即缴费</view>
				</view>
			</view>
		</view>
		<!-- 弹出步进器 -->
		<u-popup v-model="show" mode="bottom" length="35%">
			<view class="bjq">
				<u-number-box v-model="num" :min="1" :input-width="100" :input-height="60"></u-number-box>
				<view class="u-flex u-row-between">
					<u-button size="medium" @click="cancel" :custom-style="customStyle">取消</u-button>
					<u-button type="warning" size="medium" @click="confirm" :custom-style="customStyle">确认</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { log } from '../../js_sdk/hhyang-uni-simple-router/helpers/warn';
	export default {
		data() {
			return {
				costRemarks: '',
				num: 1,
				show: false,
				allchecked: false, //全选
				name: '',
				address: '',
				customStyle: {
					margin: '40rpx', // 注意驼峰命名，并且值必须用引号包括，因为这是对象
				},
				data: {
					id: '',
					mobile: '',
					proId: '',
					code: '',
					name: '',
					address: '',
					money: '',
					setId: '',
					childList: []
				},
				homelist: {},
				payList: {},
				//物业费合计
				payTotal: 0,
				//前端分开渲染考虑有100条数据，渲染展示了默认10条，setTimeout慢慢渲染有些不好，所以用 ture 判断了
				isShow: false,
				//保存总金额
				totalMon: null,
				roomInfo: [],
				//保存总金额
				totalMon: null,
				//微信
				weChat: true,
				//支付宝
				alipay: false,


				//支付宝支付
				title: 'request-payment',
				loading: false,
				price: 1,
				providerList: [],
				userObj: {},

				//微信支付
				allmoney: '3600.00',
				type: '已支付',
				num: 'WY20200807',
				billList: {},
				money: '',
				timeHand: false,
				
				openId:'',
			}
		},
		onShow() {
			this.checkLogin()
			if (uni.getStorageSync('hourseList')) {
				this.homelist = uni.getStorageSync('hourseList')[uni.getStorageSync('hourseNum') || 0]
				this.name = this.homelist.proName;
				this.address = this.homelist.buildDistrictCode + '-' + this.homelist.buildTowerCode + '-' + this.homelist
					.roomUnitNumber +
					'-' + this.homelist.roomCode
			}

			this.getPayDetails()
			this.totalMon = 0;
			// this.getBillDetail()
		},
		methods: {

			checkLogin() {
				let _this = this
				if (uni.getStorageSync('phone')) {
					if (uni.getStorageSync('loginFlag')) {
						if (!uni.getStorageSync('hourseList')) {
							uni.showModal({
								title: '请先进行业主认证',
								showCancel: false,
								confirmText: '确认',
								confirmColor: '#F9A832',
								success: function(res) {
									if (res.confirm) {
										_this.$Router.push({
											path: '/my/address/address'
										})
									}
								}
							});
							this.$openInvite()
						} else {
							_this.showFlag = true
							_this.homelist = uni.getStorageSync('hourseList')[uni.getStorageSync('hourseNum') || 0]
							_this.name = _this.homelist.proName;
							_this.address = _this.homelist.buildDistrictCode + '-' + _this.homelist.buildTowerCode + '-' +
								_this.homelist.roomUnitNumber + '-' + _this.homelist.roomCode

							this.homelist = uni.getStorageSync('hourseList')[uni.getStorageSync('hourseNum') || 0]
							// this.getList()
						}
					} else {
						uni.showModal({
							title: '请先实名认证',
							showCancel: false,
							confirmText: '确认',
							confirmColor: '#F9A832',
							success: function(res) {
								if (res.confirm) {
									_this.$Router.push({
										path: '/homePage1/realName/realName'
									})
								}
							}
						});
					}
				} else {
					uni.showModal({
						title: '请先登录',
						showCancel: false,
						confirmText: '确认',
						confirmColor: '#F9A832',
						success: function(res) {
							if (res.confirm) {
								_this.$Router.pushTab({
									path: '/pages/user/user'
								})
							}
						}
					});
				}
				uni.stopPullDownRefresh()

			},

			//点击选择方式
			handleTime() {
				if (this.timeHand == false) {
					this.timeHand = true
				} else {
					this.timeHand = false
				}
			},
			//点击微信支付
			handleWechat(num) {
				if (num == 1) {
					this.weChat = true
					this.alipay = false
				} else {
					this.alipay = true
					this.weChat = false
				}
			},
			handleAdditional(item,index){
				if(item.selectionStatus2){
					this.payTotal = (parseFloat(this.payTotal) + parseFloat(item.weiYueMoney)).toFixed(2);
				}else{
					this.payTotal = (parseFloat(this.payTotal) - parseFloat(item.weiYueMoney)).toFixed(2);
				}
				//console.log(this.payTotal)
			},
			async getPayDetails() {
				uni.showLoading({
					title: '加载订单中'
				});
				let res = await this.$request.api.payDetails({
					proId: this.homelist.proId,
					roomId: this.homelist.roomId,
					setId: this.homelist.setId,
				})
				this.payList = res.data.data
				this.roomInfo = res.data.data.wuYeCost
				// 显示数据

				this.isShow = true
				this.timeHand = true
				uni.hideLoading();
				this.totalMoney();
			},
			//计算总计
			totalMoney() {
				let payArr = this.payList.wuYeCost;
				this.payTotal = 0;
				payArr.forEach(item => {
					this.payTotal = this.add(this.payTotal, item.allMoney)
					//console.log(this.payTotal)
				})
			},

			// 预缴费用
			async confirm() {
				let res = await this.$request.api.prePay({
					proId: this.homelist.proId,
					roomId: this.homelist.roomId,
					// roomId:17706,
					setId: this.homelist.setId,
					num: this.num
				})
				this.show = false
				if (res.data.status == 200) {
					this.allchecked = false;
					this.payTotal = 0;
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'error'
					});
				}
				this.getPayDetails()
				this.num = 1;

			},
			async payBtn() {
				uni.showLoading({
					title: '加载中...'
				});
				if (this.payTotal) {
					let periodList = [];
					this.payList.wuYeCost.filter(item => {
						periodList.push(item)
					})
					let res = await this.$request.api.payOrder({
						allMoney: this.payTotal,
						roomId: this.homelist.roomId,
						phone: uni.getStorageSync('phone'),
						periodList: periodList,
						proId: this.homelist.proId,
						costRemarks: this.costRemarks
					}).then(res => {
						this.idRes = res.data.data
						this.getBillDetail(this.idRes)
					})
				}
			},
			async getBillDetail(val) {
				let res = await this.$request.api.billDetails({
					setId: this.homelist.setId,
					id: val,
					mobile: uni.getStorageSync('phone')
				})
				this.billList = res.data.data
				this.payClick()
			},
			async payClick() {
				let that = this;
				let openId = uni.getStorageSync('openId');
				if(!openId){
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							uni.setStorageSync('code', loginRes.code);
							uni.request({
								url: 'https://admin.515f.com/weixin/applet/get_openid_by_code', //仅为示例，并非真实接口地址。
								data: {
									code: loginRes.code
								},
								method:'post',
								success: function(res) {
									let obj = res.data.data.data;
									uni.setStorageSync('openId', obj.openId);
									that.openId = obj.openId
									uni.setStorageSync('sessionKey', obj.sessionKey);
									that.payFn(that.openId)
								}
							});
						}
					})
				}else{
					this.payFn(openId)
				}
			},
			async payFn(openId){
				
					let res = await this.$request.api.getWxPay({
						id: this.idRes,
						mobile: uni.getStorageSync('phone'),//this.data.mobile,
						open_id: openId,//this.openId || uni.getStorageSync('openId'),
						proId: this.homelist.proId,
						pay_type: 'wx_lite', //（支付渠道）
						goods_title: '小程序物业收费', //（商品标题）
						goods_desc: '小程序物业收费', //（商品描述信息）
						allMoney: Number(this.payTotal).toFixed(2),
						code: this.billList.order.code
					})
					if (res.data.status != 200) {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
						return
					}
					uni.hideLoading();
					let pay_info = JSON.parse(res.data.data.expend.pay_info)
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: pay_info.timeStamp,
						nonceStr: pay_info.nonceStr,
						package: pay_info.package,
						signType: pay_info.signType,
						paySign: pay_info.paySign,
						success: function(res) {
							that.getBillDetail();
						},
						fail: function(err) {
							uni.showToast({
								icon: 'none',
								title: '取消支付'
							})
						}
					});
			},

			// 取消
			cancel() {
				this.num = 1;
				this.show = false
			},
			selectAllBtn() {
				let payArr = this.payList.wuYeCost;
				this.payTotal = 0;
				payArr.forEach(item => {
					if (this.allchecked == false) {
						item.wuyechecked = false
						this.payTotal = 0
					} else {
						if (!item.freeOrder) {
							item.wuyechecked = true
							this.payTotal = this.add(this.payTotal, item.allMoney)
						}
					}
				})
			},
			// 定义加法函数
			add() {
				let args = arguments, //获取所有的参数
					lens = args.length, //获取参数的长度
					d = 0, //定义小数位的初始长度，默认为整数，即小数位为0
					sum = 0; //定义sum来接收所有数据的和
				//循环所有的参数
				for (let key in args) {
					//遍历所有的参数
					//把数字转为字符串
					let str = '' + args[key];
					if (str.indexOf('.') != -1) {
						//判断数字是否为小数
						//获取小数位的长度
						let temp = str.split('.')[1].length;
						//比较此数的小数位与原小数位的长度，取小数位较长的存储到d中
						d = d < temp ? temp : d;
					}
				}
				//计算需要乘的数值
				let m = Math.pow(10, d);
				//遍历所有参数并相加
				for (let key in args) {
					sum += args[key] * m;
				}
				//返回结果
				return Number(sum / m).toFixed(2);
			},
			// 定义减法
			sub(num1, num2) {
				let r1, r2, m, n;
				try {
					r1 = num1.toString().split('.')[1].length;
				} catch (e) {
					r1 = 0;
				}
				try {
					r2 = num2.toString().split('.')[1].length;
				} catch (e) {
					r2 = 0;
				}
				m = Math.pow(10, Math.max(r1, r2));
				return (Math.round(num1 * m - num2 * m) / m).toFixed(2);
			},
			changePay(item, index) {
				let payArr = this.payList.wuYeCost;
				console.log(payArr)
				this.allchecked = true
				let a = 0;

				console.log(index)
				if (item.costSign == 3) {
					console.log("全选业务")
					//从前往后选择订单业务
					if (!item.wuyechecked) {
						for (let i = index; i < this.payList.wuYeCost.length; i++) {
							if (this.payList.wuYeCost[i].costSign == 3) {
								this.$set(this.payList.wuYeCost[i], 'wuyechecked', false);
							}
						}
					} else {
						for (let i = 0; i < index; i++) {
							if (this.payList.wuYeCost[i].costSign == 3) {
								this.$set(this.payList.wuYeCost[i], 'wuyechecked', true);
								this.payTotal = this.add(this.payTotal, this.payList.wuYeCost[i].allMoney)
							}
						}
					}
				}
				if (payArr.length > 0) {
					this.payTotal = 0;
					payArr.map((item) => {
						if (!item.freeOrder) {
							if (!item.wuyechecked) {
								this.allchecked = false;
							} else {
								this.payTotal = this.add(this.payTotal, item.allMoney)
							}
						}
					});
				} else {
					this.allchecked = true;
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	page {
		background-color: #f4f4f4;
	}
.wuyepay{
	.box {
		padding: 40rpx 20rpx;
		background: rgba(244, 244, 244, 1);
		border-radius: 6px;
		margin-top: 10rpx;

		view {
			display: inline-block;
			width: 50%;
			margin-bottom: 10rpx;
		}
	}

	.btn {
		text-align: center;
		width: 290rpx;
		height: 92rpx;
		border-radius: 50rpx;
		border: 1px solid #42770591;
		line-height: 92rpx;
		color: #42770591;
		font-size: 32rpx;
		margin: 40rpx auto;
	}

	.head {
		border-top: 1px solid rgba(0, 0, 0, .1);
		background: #f4f4f4;
		padding: 16rpx;
	}

	.main_top {
		height: 80rpx;
		background: rgba(244, 244, 244, 1);
	}

	.foot .footer {
		width: 100%;
		height: 136rpx;
		position: fixed;
		bottom: 0;
		z-index: 99;
		background: rgba(255, 255, 255, 1);
		box-shadow: 28px 1px 6px rgba(0, 0, 0, 0.15);
	}

	.txet {
		color: #FD3636;
	}

	.main {
		margin-bottom: 300rpx;
		padding: 20rpx;
		margin-top: -17px;
	}

	.mian_content {
		background: #fff;
		padding: 20rpx 30rpx;
		margin-top: 22rpx;
	}

	.mian_content1 {
		background: #fff;
		padding: 38rpx 36rpx;
		margin-top: 22px;
		border-radius: 16px;
		display: flex;
		justify-content: space-between;
	}

	.button {
		text-align: center;
		background: linear-gradient(142deg, #42770591 0%, #427705FF 100%);
		color: #fff;
		padding: 7px 18px;
		border-radius: 8px;
		margin-right: 10px;
		margin-top: 15px;
	}
	.bjq {
		padding-top: 15%;
		padding-left: 60rpx;
		padding-right: 60rpx;
	}
	.property-cost{
		display:flex;
		align-items: center;
		padding:40rpx 0px;
		.property-cost-mark{
			padding: 5px 11px;
			background-color: #fff;
			margin-top: -6px;
			flex:1;
		}
	}
}
</style>
<style lang="scss">
	.bjq {
		.u-numberbox {
			display: flex !important;
			justify-content: space-between !important;
			width: 100% !important;
			border-top: 1px solid #427705FF;
			border-bottom: 1px solid #427705FF;
			padding: 40rpx 0;
		}
		.u-number-input {
			background-color: #fff !important;
		}
	}
	.position-name {
		font-size: 38rpx;
		font-weight: 550;
		color: #333333;
	}
	.position-name i {
		width: 6px;
		height: 16px;
		background: linear-gradient(180deg, #76D904 0%, #417505 100%);
		border-radius: 4px;
		display: inline-block;
		vertical-align: middle;
		margin-top: -3px;
	}

	.pay-count {
		font-size: 36rpx;
		font-weight: 600;
		color: #F9A832;
		align-items: center;
		margin-top: -12px;
		float: right;
	}

	.border-back {
		background: rgb(255, 255, 255);
		width: 100%;
		margin: auto;
		border-radius: 10px;
		box-shadow: 0 1px 6px rgba(0, 0, 0, 0.15);
		padding: 20rpx 44rpx;
	}

	.daishenpi {
		width: 106rpx;
		height: 44rpx;
		line-height: 44rpx;
		text-align: center;
		color: #FFFFFF;
		background: linear-gradient(90deg, #ebb15ddb 0%, #f9a832 100%);
		border-radius: 6rpx;
		margin-left: 20rpx;
		font-size: 28rpx;
		border-radius: 12rpx 0;
	}

	.jujue {
		width: 106rpx;
		height: 44rpx;
		line-height: 44rpx;
		text-align: center;
		color: #FFFFFF;
		background: linear-gradient(90deg, #FF6666 0%, #FD3636 100%);
		border-radius: 6rpx;
		margin-left: 20rpx;
		font-size: 28rpx;
		border-radius: 12rpx 0;
	}

	.youxiao {
		width: 106rpx;
		height: 44rpx;
		line-height: 44rpx;
		text-align: center;
		background: linear-gradient(90deg, #00aa00 0%, #55aa00 100%);
		border-radius: 6rpx;
		color: #FFFFFF;
		margin-left: 20rpx;
		font-size: 24rpx;
		border-radius: 12rpx 0;
	}

	.mainpayment {
		padding: 10px;
		position: fixed;
		bottom: 52px;
		width: 100%;
	}
</style>